package com.sinnatec.redis.lock.impl;


import org.springframework.data.redis.core.StringRedisTemplate;
import com.sinnatec.redis.lock.RedisLock;

import java.util.UUID;

/**
 * @ClassName AbstractRedisLock
 * @Description redis分布式锁抽象类
 * @Author fangsong
 * @Date 2021/12/6 16:04
 * @Version 1.0
 */
public abstract class AbstractRedisLock implements RedisLock {

    /**
     * 默认等待获取锁超时时长，获取不到立即返回
     */
    private static final long DEFAULT_WAIT_TIME = 5000L;

    /**
     * 默认锁存在时长
     */
    private static final long DEFAULT_LEASE_TIME = 30000L;

    private static final String LOCK_NAME_PREFIX = "DISTRIBUTEDLOCK::LOCK::";

    /**
     * 锁名称
     */
    private final String lockName;
    /**
     * 唯一标识
     */
    private final String transId;

    private final StringRedisTemplate redisTemplate;

    protected AbstractRedisLock(StringRedisTemplate redisTemplate, String lockName) {
        this.redisTemplate = redisTemplate;
        this.lockName = lockName;
        transId = generateTransId();
    }

    /**
     * 生成锁唯一标识
     *
     * @return
     *              唯一标识
     */
    protected String generateTransId(){
        return UUID.randomUUID().toString().replace("-","");
    }

    /**
     * 获取锁存在时长
     *
     * @return
     *              存在时长，单位毫秒
     */
    protected long getLeaseTime(){
        return DEFAULT_LEASE_TIME;
    }

    /**
     * 获取等待获取锁超时时长
     *
     * @return
     *              超时时长
     */
    protected long getWaitTime(){
        return DEFAULT_WAIT_TIME;
    }

    public String getLockName() {
        return LOCK_NAME_PREFIX+lockName;
    }

    public String getTransId() {
        return transId;
    }

    protected StringRedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

}
